#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;


int main()
{
    CascadeClassifier cascade;
    cascade.load("../../resource/data/haarcascades/haarcascade_frontalface_alt2.xml");
    VideoCapture cap(0);
    if (!cap.isOpened())
        return -1;
    Mat frame, myFace;
    int picNum = 1;
    while (1) {
        cap >> frame;
        vector<Rect> faces;
        Mat frameGray;
        cvtColor(frame, frameGray, CV_BGR2GRAY);
        cascade.detectMultiScale( frameGray, faces );
        printf( "检测到的人脸个数: %d\n", faces.size() );

        //识别到的人脸用矩形框框处
        for (size_t i = 0; i < faces.size(); i++) {
            rectangle(frame, faces[i], Scalar(255, 0, 0), 2, 8, 0);
        }
        if (faces.size() == 1) {
            Mat faceROI = frameGray(faces[0]);
            resize(faceROI, myFace, Size(92, 112));
            putText(frame, to_string(picNum), faces[0].tl(), 3, 1.2, Scalar(0, 0, 255),
                    2, 0);
            string fileName = format("../../resource/image/faces/BelingBeling/%d.png", picNum);
            imwrite(fileName, myFace);
            imshow(fileName, myFace);
            imshow("frame", frame);
            while (waitKey(100) == -1) {
                //延迟 等待按键
            }
            destroyAllWindows();
            picNum++;
            if (picNum == 11)
                return 0;
        }
    }


    return 0;
}
